import api from "../../../common/api.js";
Page({
  data: {
    bgUrl: '', //背景图链接
    windowWidth: 0, //屏幕宽度
    windowHeight: 0, //屏幕高度
    contentHeight: 0, //内容高度
    thinkList: [], //文字超出换行处理
    lineHeight: 30, //固定值
    contentTitle: "", //经纪人名称
    qrCode: "https://api-dev.shulanfd.com/aist-filesvr-web/api/files/b4fe95788ba14114b869c251258adbee", //小程序码https图片路径
    // qrCode: "https://api-dev.shulanfd.com/aist-filesvr-web/api/files/c0cfc8bba1c34d7c98aaf86814ba154f", //小程序码https图片路径
    goodsInfoImg: "", //背景图片
    avatar: '',//头像
    mobileText: "", //手机号
    storeName: "",//店铺
  },
  getUserInfo() {
    let that = this;
    api.getSessionInfo(null, function(res) {
      let data = res.data.content;
      that.setData({
        contentTitle: `${data.realName}(您的专属经纪人)`,
        mobileText: `手机号：${data.mobile}`,
        avatar: data.avatar,
        storeName: data.extProps.storeName?`门店名：${data.extProps.storeName}`:null
      })
    })
  },
  onLoad(options) {

    let that = this;
    that.setData({
      bgUrl: options.url
    })
    that.getUserInfo();
    //获取设备信息高度。计算出其他的高度等
    wx.getSystemInfo({
      success(res) {
        that.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowWidth * 1.7773333333333334,
          normalPageX: 0, //左边文本图片X轴位置
          boxWidth: res.windowWidth, //分享图片box宽度
          boxheight: res.windowWidth * 1.7773333333333334, //分享图片box高度
          boxPageY: 0, //boxY轴位置
          imgWidth: res.windowWidth, //背景图片宽度
          imgHeight: res.windowWidth * 1.7773333333333334, //背景图片高度
          imgPageY: 0, //背景图片Y轴位置
          codeWidth: 60, //小程序码图片宽度
          codeHeight: 60, //小程序码图片高度
          codePageY: res.windowWidth * 1.7773333333333334 - 100,//小程序码Y轴位置
          // avatarPageY: res.windowWidth * 0.222 + res.windowWidth * 0.72 + 15, //头像Y轴位置
          titlePageY: res.windowWidth * 1.7773333333333334 - 95, //标题Y轴位置
          mobilePageY: res.windowWidth * 1.7773333333333334 - 80, //手机号Y轴位置
        });
      }
    });
    //网络图片转为本地图片，直接显示网络图片的话真机不显示
    that.getTempFile(options.url);
  },

  getData() {
    let that = this;

    let i = 0;
    let lineNum = 1;
    let thinkStr = "";
    let thinkList = [];
    for (let item of that.data.contentTitle) {
      if (item === "\n") {
        thinkList.push(thinkStr);
        thinkList.push("a");
        i = 0;
        thinkStr = "";
        lineNum += 1;
      } else if (i === 21) {
        thinkList.push(thinkStr);
        i = 1;
        thinkStr = item;
        lineNum += 1;
      } else {
        thinkStr += item;
        i += 1;
      }
    }
    thinkList.push(thinkStr);
    that.setData({
      thinkList: thinkList
    });
    that.createNewImg(lineNum);
  },

  //画矩形，也是整块画布的大小，宽度是屏幕宽度，高度根据内容多少来动态设置。
  drawSquare(ctx, height) {
    let that = this;
    ctx.rect(
      that.data.normalPageX,
      that.data.boxPageY,
      that.data.boxWidth,
      height
    );
    ctx.setFillStyle("#f6f6f6");
    ctx.fill();
  },

  // 设置文字大小，并填充颜色。
  drawFont(ctx, contentTitle, height) {
    let that = this;
    let str = that.data.contentTitle;
    let firstline;
    let secondline;
    //一行显示12个字，超过一行时
    if (str.length > 12) {
      //第一行截取前12个字符
      firstline = str.substring(0, 14);
      //两行都显示不下
      if (str.length > 28) {
        secondline = str.substr(14, 14) + "...";
      } else {
        //第二行取剩下的
        secondline = str.substr(14, str.length - 14);
      }
    } else {
      //一行就能显示时候
      firstline = str;
    }

    ctx.setFontSize(14);
    ctx.setFillStyle("#fdebb6");
    ctx.fillText(firstline, that.data.normalPageX + that.data.codeWidth * 0.9 + 22, that.data.titlePageY + 10);
    if (secondline) {
      ctx.setFontSize(12);
      ctx.setFillStyle("#fdebb6");
      ctx.fillText(
        secondline,
        that.data.normalPageX + that.data.codeWidth * 0.9 + 22,
        that.data.titlePageY+25
      );
    }
    if (that.data.mobileText) {
      ctx.setFontSize(12);
      ctx.setFillStyle("#fdebb6");
      ctx.fillText(
        that.data.mobileText,
        that.data.normalPageX + that.data.codeWidth * 0.9+22,
        that.data.mobilePageY + (secondline?30:20)
      );
    }
    if (that.data.storeName) {
      ctx.setFontSize(12);
      ctx.setFillStyle("#fdebb6");
      ctx.fillText(
        that.data.storeName,
        that.data.normalPageX + that.data.codeWidth * 0.9 + 22,
        that.data.mobilePageY + (secondline ? 50 : 40)
      );
    }
  },
  // 根据文字多少动态计算高度，然后依次画出矩形，文字，横线和小程序码。
  createNewImg(lineNum) {
    let that = this;
    let ctx = wx.createCanvasContext("myCanvas");
    let contentHeight = that.data.boxheight;
    that.drawSquare(ctx, contentHeight);
    that.setData({
      contentHeight: contentHeight
    });
    //背景图片
    ctx.drawImage(
      that.data.goodsInfoImg,
      that.data.normalPageX,
      that.data.imgPageY,
      that.data.imgWidth,
      that.data.imgHeight
    );
    // 头像
    var avatarurl_width = that.data.codeWidth * 0.8;    //绘制的头像宽度
    var avatarurl_heigth = that.data.codeWidth * 0.8;   //绘制的头像高度
    var avatarurl_x = that.data.normalPageX + 20;   //绘制的头像在画布上的位置
    var avatarurl_y = that.data.codePageY + 8;   //绘制的头像在画布上的位置
    ctx.save();
    ctx.beginPath(); //开始绘制
    //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
    ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
    ctx.clip();//画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因
    ctx.drawImage(that.data.avatar, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth); // 推进去图片，必须是https图片
    ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制

    let height = 100;
    for (let item of that.data.thinkList) {
      if (item !== "a") {
        that.drawFont(ctx, item, height);
        height += that.data.lineHeight;
      }
    }
    // 填充小程序码
    ctx.drawImage(
      that.data.qrCode,
      that.data.windowWidth - 80,
      that.data.codePageY,
      that.data.codeWidth,
      that.data.codeHeight
    );
    // 长按送祝福
    ctx.setFillStyle("#fff");
    ctx.font = "normal normal 12px sans-serif";
    ctx.fillText(
      "长按送祝福",
      that.data.windowWidth - 80 + (that.data.codeWidth - 62) / 2,
      that.data.codePageY + that.data.codeWidth + 16
    );
    ctx.draw(); //绘制到canvas
  },

  //临时图片路径并下载到本地
  getTempFile(url) {
    wx.showLoading({});
    let that = this;
    wx.downloadFile({
      url: url,
      success(res) {
        that.setData({
          goodsInfoImg: res.tempFilePath
        });
        //继续生成小程序码
        wx.downloadFile({
          url: that.data.qrCode,
          success(res) {
            that.setData({
              qrCode: res.tempFilePath
            });
            wx.hideLoading();
            //生成数据
            that.getData();
          },
          fail(err) {
            wx.showToast({
              title: "下载失败,稍后重试！",
              icon: "none",
              duration: 5000
            });
          }
        });
        wx.downloadFile({
          url: that.data.avatar,
          success(res) {
            that.setData({
              avatar: res.tempFilePath
            });
            wx.hideLoading();
            //生成数据
            that.getData();
          },
          fail(err) {
            wx.showToast({
              title: "下载失败,稍后重试！",
              icon: "none",
              duration: 5000
            });
          }
        });
      },
      fail(err) {}
    });
  },
  //点击保存到相册
  saveShareImg() {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function() {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success(res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧去送祝福吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success(res) {
                  if (res.confirm) {}
                },
                fail(res) {}
              })
            },
            fail(res) {
              if (!res) return
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  }
});